﻿using System;
using System.ComponentModel;
using MvvmFx.Common.ViewModels;
using MvvmFx.Common.ViewModels.Behaviors.Validation;

namespace MvvmFx.Samples.HowTos.Validation
{
    public class ValidatableObject : ViewModelBase,
                                     IValidatable,
                                     IDataErrorInfo
    {
        private readonly ValidationService _validation;

        public ValidatableObject()
        {
            _validation = new ValidationService(this);
        }

        #region IValidatable Members

        public ValidationService Validation
        {
            get { return _validation; }
        }

        #endregion

        #region IDataErrorInfo

        string IDataErrorInfo.Error
        {
            get
            {
                if (!_validation.IsSelfValid)
                    return _validation.ValidationRules.GetBrokenRules().ToString(
                        Common.ViewModels.Behaviors.Validation.RuleSeverity.Error);
                else
                    return String.Empty;
            }
        }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                string result = string.Empty;
                if (!_validation.IsSelfValid)
                {
                    BrokenRule rule =
                        _validation.ValidationRules.GetBrokenRules().GetFirstBrokenRule(columnName);
                    if (rule != null)
                        result = rule.Description;
                }
                return result;
            }
        }

        #endregion
    }
}